import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';
import {
  TextArea,
  TextField,
  Select,
  Button,
  Col,
  Row
} from '@folio/stripes/components';
import ImageUpload from '../../util/ImageUpload';
import { notFuzzyQueryCreate, paramReplace } from '../../util/QueryParamEdit';

function asyncValidate(values, dispatch, props, blurredField) {
  const { httpValidatorInvoke, initialValues } = props;

  if (values[blurredField]) {
    values[blurredField] = values[blurredField].trim();
  }

  const curValue = values[blurredField];

  if (!!initialValues && initialValues.id) {
    const prevValue = initialValues[blurredField];
    if (curValue !== prevValue) {
      return asyncValidateField(blurredField, curValue, httpValidatorInvoke);
    } else {
      return new Promise((resolve, reject) => {
        return resolve();
      });
    }
  } else if (blurredField) {
    const promises = [];
    promises.push(
      asyncValidateField(
        blurredField,
        values[blurredField],
        httpValidatorInvoke
      )
    );
    return Promise.all(promises);
  } else {
    return Promise.all([]);
  }
}

function asyncValidateField(field, value, validator) {
  return new Promise((resolve, reject) => {
    const query = {};
    query[field] = value;

    const param = notFuzzyQueryCreate(query);
    const queryParam = paramReplace('( isDel = 0 %{query})', param);
    validator.reset();
    return validator.GET({ params: { query: queryParam } }).then(result => {
      if (result.totalRecords > 0) {
        const error = {};
        error[field] =  <FormattedMessage id={"ui-party.other.already.exists"}></FormattedMessage>;
        // <FormattedMessage id="ui-activity.messageTemplate.data.name.error"/>
        return reject(error);
      } else {
        return resolve();
      }
    });
  });
}

function validate(values, props) {
  const errors = {};

  if (!values || !values.name) {
    errors.name = (
      <FormattedMessage id="ui-party.errors.missingRequiredField" />
    );
  }
  if (!values || !values.typeName) {
    errors.typeName = (
      <FormattedMessage id="ui-party.errors.missingRequiredField" />
    );
  }
  if (!values || !values.amount) {
    errors.amount = (
      <FormattedMessage id="ui-party.errors.missingRequiredField" />
    );
  }
  if (!values || !values.state) {
    errors.state = (<FormattedMessage id="ui-party.errors.missingRequiredField" />);
  }
  return errors;
}

class EditForm extends Component {
  // eslint-disable-next-line react/sort-comp
  constructor(props) {
    super(props);
    this.state = {
      open: true,

      show: false,
      editsStatus: 'success',

    };
  }

  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    // eslint-disable-next-line react/no-unused-prop-types
    initialValues: PropTypes.object,
    // eslint-disable-next-line react/no-unused-prop-types
    dictionary: PropTypes.object,
    // eslint-disable-next-line react/no-unused-prop-types
    cleanSearch: PropTypes.func,
    intl: PropTypes.func,
    cancel: PropTypes.func,

    imageUploadHttpInvoke:PropTypes.func,
    stripes:PropTypes.object,
  };

  render() {
    const footer = (

      <div>
        <Button onClick={this.props.cancel}>
          <FormattedMessage id="ui-party.cancel" />
        </Button>
        <Button buttonStyle="primary" marginBottom0 type="submit">
          <FormattedMessage id="ui-party.saveAndExit" />
        </Button>
      </div>

    );
    const { handleSubmit, intl } = this.props;
    //console.log(this.props);
    return (
      <Row center="xs" style={{ width: '100%' }}>
        <Col xs={6}>
          <form data-test-form-page id="form-add" onSubmit={handleSubmit}>
            <Field
              component={TextField}
              name="name"
              label={
                <FormattedMessage id="ui-party.loans.columns.source.name" />
              }
              required
            />
            <Field
              component={Select}
              name="typeName"
              dataOptions={[
                {
                  id: '0',
                  value: '',
                  label: intl.formatMessage({ id: 'ui-party.other.please.select.facility.type' }) 
                },
                {
                  id: '1',
                  value: 1,
                  label: intl.formatMessage({ id: 'ui-party.loans.columns.source.venue' })  
                },
                {
                  id: '2',
                  value: 2,
                  label: intl.formatMessage({ id: 'ui-party.loans.columns.source.device' })   
                }
              ]}
              label={
                <FormattedMessage id="ui-party.loans.columns.source.type" />
              }
              required
            />
            <Field
              component={TextField}
              name="amount"
              hasClearIcon
              type="number"
              min="1"
              max="9999"
              label={<FormattedMessage id="ui-party.loans.columns.source.amount" />}
              required
            />

            <Field
              required
              component={Select}
              name="state"
              label={<FormattedMessage id="ui-party.loans.columns.source.state" />}
              dataOptions={[
                {
                  id: '0',
                  value: '',
                  label: intl.formatMessage({ id: 'ui-party.other.please.select.resource.status' })  
                },
                {
                  id: '1',
                  value: 1,
                  label: intl.formatMessage({ id: 'ui-party.loans.columns.party.effective' })  
                },
                {
                  id: '2',
                  value: 0,
                  label: intl.formatMessage({ id: 'ui-party.loans.columns.party.noneffective' })   
                }
              ]}
            />
            <Field
              label={<FormattedMessage id={"ui-party.other.resource.picture"}/>}
              labelName={<FormattedMessage id={"ui-party.other.resource.picture"}/>}
              requiredFlag={false}
              component={ImageUpload}
              name="picturesId"
              imageUploadHttpInvoke={this.props.imageUploadHttpInvoke}
              stripes={this.props.stripes}
            />

            <Field
              component={TextArea}
              name="depict"
              label={
                <FormattedMessage id="ui-party.loans.columns.source.description" />
              }
              style={{ height: '150px' }}
            />
            {footer}
          </form>
        </Col>

        {/* {this.props.exitFlag && <Prompt message="确定要退出当前页面？" when />} */}
      </Row>
    );
  }
}

export default injectIntl(
  reduxForm({
    form: 'equipmentEditForm' + new Date().getTime(),
    validate,
    asyncValidate,
    asyncBlurFields: ['name'],
    navigationCheck: true,
    enableReinitialize: true
  })(EditForm)
);
